package org.minuframework.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

public final class JdbcPool{
    
    protected JdbcProperties         jdbcProperties;
    protected LinkedList<Connection> connectionList;
    
    public LinkedList<Connection> getParamerRepository(){
        if (connectionList == null) {
            connectionList = new LinkedList<Connection>();
            while (connectionList.size() < jdbcProperties.getMaxActive()) {
                connectionList.add(JdbcConnection.openConnection(jdbcProperties));
            }
        }
        return connectionList;
    }
    
    public JdbcProperties getJdbcProperties(){
        return jdbcProperties;
    }
    
    public void setJdbcProperties(JdbcProperties jdbcProperties){
        this.jdbcProperties = jdbcProperties;
    }
    
    public synchronized Connection getConnection(){
        return this.connectionList.removeFirst();
    }
    
    public void releaseConnection(Connection conn){
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                this.connectionList.add(JdbcConnection.openConnection(jdbcProperties));
            }
        }
    }
    
    public void creatConnection(Connection conn){}
    
    public void release(PreparedStatement preparedStatement, Statement statement, ResultSet resultSet){
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (resultSet != null) {
                resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
}
